﻿namespace PlugNT.Database.Common.Entity
{
    using PlugNT.Custom;
    using PlugNT.Database.Common;
    using PlugNT.Database.Common.Complex;
    using PlugNT.Safe;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Runtime.InteropServices;

    public class DbHelper
    {
        private DbConnection connection;
        private DbDataAdapter dadapter;
        public DbInfo dbinfo;

        public DbHelper()
        {
            this.dbinfo = new DbInfo(WebConfig.DbType, WebConfig.ConnectionString);
            this.Init(this.dbinfo);
        }

        public DbHelper(DbInfo dbInfo)
        {
            this.Init(dbInfo);
        }

        private void BuildIntCommand(DbCommand command, DbConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            this.BuildQueryCommand(command, storedProcName, parameters);
            command.Parameters.Add(DbProvider.MakeIntParam(this.dbinfo, "ReturnValue"));
        }

        private void BuildQueryCommand(DbCommand command, string storedProcName, IDataParameter[] parameters)
        {
            command.CommandText = storedProcName;
            command.CommandType = CommandType.StoredProcedure;
            foreach (DbParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }
        }

        public void CloseConnection()
        {
            if (this.connection.State != ConnectionState.Closed)
            {
                this.connection.Close();
            }
        }

        public bool ColumnExists(string tableName, string columnName)
        {
            string sQLString = "select count(1) from syscolumns where [id]=object_id('" + StringHelper.SqlFilter(tableName) + "') and [name]='" + StringHelper.SqlFilter(columnName) + "'";
            object single = this.GetSingle(sQLString);
            if (single == null)
            {
                return false;
            }
            return (Convert.ToInt32(single) > 0);
        }

        public DbDataReader ExecuteReader(string SQLString)
        {
            DbDataReader reader2;
            try
            {
                this.OpenConnection();
                DbCommand command = this.connection.CreateCommand();
                command.Connection = this.connection;
                command.CommandText = SQLString;
                DbDataReader reader = command.ExecuteReader();
                command.Dispose();
                command = null;
                reader2 = reader;
            }
            catch (DbException exception)
            {
                throw exception;
            }
            return reader2;
        }

        public DbDataReader ExecuteReader(string SQLString, params DbParameter[] cmdParms)
        {
            DbDataReader reader2;
            try
            {
                this.OpenConnection();
                DbCommand cmd = this.connection.CreateCommand();
                PrepareCommand(cmd, this.connection, null, SQLString, cmdParms);
                DbDataReader reader = cmd.ExecuteReader();
                cmd.Dispose();
                cmd = null;
                reader2 = reader;
            }
            catch (DbException exception)
            {
                throw exception;
            }
            return reader2;
        }

        public int ExecuteSql(string SQLString)
        {
            int num2;
            try
            {
                this.OpenConnection();
                DbCommand command = this.connection.CreateCommand();
                command.Connection = this.connection;
                command.CommandText = SQLString;
                int num = command.ExecuteNonQuery();
                command.Dispose();
                command = null;
                num2 = num;
            }
            catch (DbException exception)
            {
                this.connection.Close();
                throw exception;
            }
            return num2;
        }

        public int ExecuteSql(string SQLString, params DbParameter[] cmdParms)
        {
            int num2;
            try
            {
                this.OpenConnection();
                DbCommand cmd = this.connection.CreateCommand();
                PrepareCommand(cmd, this.connection, null, SQLString, cmdParms);
                int num = cmd.ExecuteNonQuery();
                cmd.Dispose();
                cmd = null;
                num2 = num;
            }
            catch (DbException exception)
            {
                throw exception;
            }
            return num2;
        }

        public int ExecuteSqlByTime(string SQLString, int Times)
        {
            int num2;
            try
            {
                this.OpenConnection();
                DbCommand command = this.connection.CreateCommand();
                command.Connection = this.connection;
                command.CommandText = SQLString;
                command.CommandTimeout = Times;
                int num = command.ExecuteNonQuery();
                command.Dispose();
                command = null;
                num2 = num;
            }
            catch (DbException exception)
            {
                this.connection.Close();
                throw exception;
            }
            return num2;
        }

        public int ExecuteSqlTran(List<string> SQLStringList)
        {
            this.OpenConnection();
            DbCommand command = this.connection.CreateCommand();
            command.Connection = this.connection;
            DbTransaction transaction = this.connection.BeginTransaction();
            command.Transaction = transaction;
            try
            {
                int num = 0;
                for (int i = 0; i < SQLStringList.Count; i++)
                {
                    string str = SQLStringList[i];
                    if (str.Trim().Length > 1)
                    {
                        command.CommandText = str;
                        num += command.ExecuteNonQuery();
                    }
                }
                transaction.Commit();
                command.Dispose();
                command = null;
                return num;
            }
            catch
            {
                transaction.Rollback();
                return 0;
            }
        }

        public bool Exists(string strSql)
        {
            int num;
            object single = this.GetSingle(strSql);
            if (object.Equals(single, null) || object.Equals(single, DBNull.Value))
            {
                num = 0;
            }
            else
            {
                num = int.Parse(single.ToString());
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        public bool Exists(string strSql, params DbParameter[] cmdParms)
        {
            int num;
            object single = this.GetSingle(strSql, cmdParms);
            if (object.Equals(single, null) || object.Equals(single, DBNull.Value))
            {
                num = 0;
            }
            else
            {
                num = int.Parse(single.ToString());
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        ~DbHelper()
        {
            this.connection = null;
        }

        public int GetMaxID(string FieldName, string TableName)
        {
            string sQLString = "select max(" + StringHelper.SqlFilter(FieldName) + ")+1 from " + StringHelper.SqlFilter(TableName);
            object single = this.GetSingle(sQLString);
            if (single == null)
            {
                return 1;
            }
            return int.Parse(single.ToString());
        }

        public object GetSingle(string SQLString)
        {
            object obj3;
            try
            {
                this.OpenConnection();
                DbCommand command = this.connection.CreateCommand();
                command.Connection = this.connection;
                command.CommandText = SQLString;
                object objA = command.ExecuteScalar();
                command.Dispose();
                command = null;
                if (object.Equals(objA, null) || object.Equals(objA, DBNull.Value))
                {
                    return null;
                }
                obj3 = objA;
            }
            catch (DbException exception)
            {
                this.connection.Close();
                throw exception;
            }
            return obj3;
        }

        public object GetSingle(string SQLString, params DbParameter[] cmdParms)
        {
            object obj3;
            try
            {
                this.OpenConnection();
                DbCommand cmd = this.connection.CreateCommand();
                PrepareCommand(cmd, this.connection, null, SQLString, cmdParms);
                object objA = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                cmd.Dispose();
                cmd = null;
                if (object.Equals(objA, null) || object.Equals(objA, DBNull.Value))
                {
                    return null;
                }
                obj3 = objA;
            }
            catch (DbException exception)
            {
                throw exception;
            }
            return obj3;
        }

        public static string Help()
        {
            return "mailto:549002835@qq.com";
        }

        private void Init(DbInfo dbInfo)
        {
            this.dbinfo = dbInfo;
            this.connection = DbProvider.CreateConnection(this.dbinfo);
            this.connection.Open();
            this.dadapter = DbProvider.GetFactory(this.dbinfo).CreateDataAdapter();
        }

        private void OpenConnection()
        {
            if (this.connection.State != ConnectionState.Open)
            {
                this.connection.Open();
            }
        }

        private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                cmd.Transaction = trans;
            }
            cmd.CommandType = CommandType.Text;
            if (cmdParms != null)
            {
                foreach (DbParameter parameter in cmdParms)
                {
                    if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        public DataSet Query(string SQLString)
        {
            DataSet dataSet = new DataSet();
            try
            {
                this.OpenConnection();
                DbCommand command = this.connection.CreateCommand();
                command.CommandText = SQLString;
                this.dadapter.SelectCommand = command;
                command.Dispose();
                command = null;
                this.dadapter.Fill(dataSet);
            }
            catch (DbException exception)
            {
                throw new Exception(exception.Message);
            }
            return dataSet;
        }

        public DataSet Query(string SQLString, params DbParameter[] cmdParms)
        {
            this.OpenConnection();
            DbCommand cmd = this.connection.CreateCommand();
            PrepareCommand(cmd, this.connection, null, SQLString, cmdParms);
            this.dadapter.SelectCommand = cmd;
            DataSet dataSet = new DataSet();
            try
            {
                this.dadapter.Fill(dataSet, "ds");
                cmd.Dispose();
                cmd = null;
            }
            catch (DbException exception)
            {
                throw new Exception(exception.Message);
            }
            return dataSet;
        }

        public bool ReSetTable(string tabName, string idName)
        {
            this.ExecuteSql("delete from " + StringHelper.SqlFilter(tabName));
            return (this.ExecuteSql(Tables.GetReSetTableStr(this.dbinfo, tabName, idName)) > 0);
        }

        public DbDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            this.OpenConnection();
            DbCommand command = this.connection.CreateCommand();
            command.Parameters.Clear();
            this.BuildQueryCommand(command, storedProcName, parameters);
            command.CommandType = CommandType.StoredProcedure;
            DbDataReader reader = command.ExecuteReader();
            command.Dispose();
            command = null;
            return reader;
        }

        public int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            this.OpenConnection();
            DbCommand command = this.connection.CreateCommand();
            command.Parameters.Clear();
            this.BuildIntCommand(command, this.connection, storedProcName, parameters);
            rowsAffected = command.ExecuteNonQuery();
            int num = (int) command.Parameters["ReturnValue"].Value;
            command.Dispose();
            command = null;
            return num;
        }

        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            this.OpenConnection();
            DataSet dataSet = new DataSet();
            DbCommand command = this.connection.CreateCommand();
            command.Parameters.Clear();
            this.BuildQueryCommand(command, storedProcName, parameters);
            this.dadapter.SelectCommand = command;
            this.dadapter.Fill(dataSet, tableName);
            command.Dispose();
            command = null;
            return dataSet;
        }

        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
        {
            this.OpenConnection();
            DataSet dataSet = new DataSet();
            DbCommand command = this.connection.CreateCommand();
            command.Parameters.Clear();
            this.BuildQueryCommand(command, storedProcName, parameters);
            this.dadapter.SelectCommand = command;
            this.dadapter.SelectCommand.CommandTimeout = Times;
            this.dadapter.Fill(dataSet, tableName);
            command.Dispose();
            command = null;
            return dataSet;
        }

        public bool TabExists(string TableName)
        {
            int num;
            string sQLString = "select count(*) from sysobjects where id = object_id(N'[" + StringHelper.SqlFilter(TableName) + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
            object single = this.GetSingle(sQLString);
            if (object.Equals(single, null) || object.Equals(single, DBNull.Value))
            {
                num = 0;
            }
            else
            {
                num = int.Parse(single.ToString());
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        public DataTable TabQuery(string SQLString)
        {
            return this.Query(SQLString).Tables[0];
        }
    }
}

